package com.example.btalibabanacosclient;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class BtAlibabaNacosClientApplication {

	public static void main(String[] args) {
		SpringApplication.run(BtAlibabaNacosClientApplication.class, args);
	}

	@Slf4j
	@RestController
	static class TestController {

		@Resource
		LoadBalancerClient loadBalancerClient;

		@Resource
		Client client;

		@GetMapping("/test")
		public String test() {
			// 通过spring cloud common中的负载均衡接口选取服务提供节点实现接口调用
			ServiceInstance serviceInstance = loadBalancerClient.choose("bt-alibaba-nacos-server");
			String url = serviceInstance.getUri() + "/hello?name=" + "didi";
			RestTemplate restTemplate = new RestTemplate();
			String result = restTemplate.getForObject(url, String.class);
			return "Invoke : " + url + ", return : " + result;
		}

		@GetMapping("/test2")
		public String test2(){
			String result = client.hello("didi");
			return "Return: "+ result;
		}
	}

	@FeignClient("bt-alibaba-nacos-server")
	interface Client{
		@GetMapping("/hello")
		String hello(@RequestParam("name") String name);
	}

}
